package com.kzw.oa.system.web;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.kzw.core.bean.Msg;
import com.kzw.core.mapper.Jackson;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.BeanUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.util.json.JSON;
import com.kzw.core.util.web.ResponseUtils;
import com.kzw.oa.system.bean.TreeNode;
import com.kzw.oa.system.model.Dictionary;
import com.kzw.oa.system.model.GlobalType;
import com.kzw.oa.system.service.DictionaryService;
import com.kzw.oa.system.service.GlobalTypeService;

@Controller
@RequestMapping("/system/dictionary")
public class DictionaryAction {
	@Resource
	private DictionaryService dictionaryService;
	@Resource
	private GlobalTypeService globalTypeService;


	@RequestMapping("mulSave")
	@ResponseBody
	public Msg mulSave(String data) {
		if (StringUtils.isNotEmpty(data)) {
			Gson gson = new Gson();
			Dictionary[] dics = gson.fromJson(data, Dictionary[].class);

			for (int i = 0; i < dics.length; i++) {
				Dictionary dic = dictionaryService.get(dics[i].getDicId());
				try {
					BeanUtil.copyNotNullProperties(dic, dics[i]);
					dictionaryService.saveOrUpdate(dic);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
		return new Msg(true);
	}

	/**
	 * 显示列表，只显示叶子结点
	 */
	@RequestMapping("list")
	public void list(String parentId, HttpServletRequest request, HttpServletResponse response) {
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		parentId = StringUtils.defaultIfBlank(parentId, "0");
		
		filters.add(new StringPropertyFilter("EQI_leaf", "1"));
		if(!parentId.equals("0")) {

			filters.add(new StringPropertyFilter("EQL_parentId", parentId));
		}

		Page<Dictionary> page = dictionaryService.search2(pageRequest, filters);
		String json = new JSON(page).buildWithFilters(3, "parentDict");
		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 根据条目查询出字典的value并返回数组
	 */
	@RequestMapping("load")
	public void load(String itemName, HttpServletResponse response) {
		List<String> list = dictionaryService.getAllByItemName(itemName);
		StringBuffer buff = new StringBuffer("[");
		for (String value : list) {
			buff.append("'").append(value).append("',");
		}
		if (list.size() > 0) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");
		ResponseUtils.renderJson(response, buff.toString());
	}

	/**
	 * 根据itemName进行加载
	 * */
	@RequestMapping("loadItem")
	public void loadItem(String itemName, HttpServletResponse response) {
		List<Dictionary> list = dictionaryService.getByItemName(itemName);
		StringBuffer buff = new StringBuffer("[");
		for (Dictionary dic : list) {
			buff.append("[").append(dic.getDicId()).append(",'")
					.append(dic.getItemValue()).append("'],");

		}
		if (list.size() > 0) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");
		ResponseUtils.renderJson(response, buff.toString());
	}
	
	/**
	 * 根据itemName进行加载
	 * */
	@RequestMapping("loadItem2")
	public void loadItem2(HttpServletRequest request, HttpServletResponse response) {
		List<Dictionary> list = dictionaryService.search(ExtjsUtil.getFilters(request));
		StringBuffer buff = new StringBuffer("[");
		for (Dictionary dic : list) {
			buff.append("[").append(dic.getDicId()).append(",'")
					.append(dic.getItemValue()).append("'],");

		}
		if (list.size() > 0) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");
		ResponseUtils.renderJson(response, buff.toString());
	}

	@RequestMapping("loadItemRecord")
	public void loadItemRecord(String itemName, HttpServletResponse response) {
		List<Dictionary> list = dictionaryService.getByItemName(itemName);
		String json = new JSON(list).buildWithFilters(3, "parentDict", "globalType");	
		ResponseUtils.renderJson(response, json);
	}
	
	@RequestMapping("typeChange")
	@ResponseBody
	public Msg typeChange(String dicIds, String dicTypeId) {

		if (StringUtils.isNotEmpty(dicIds) && StringUtils.isNotEmpty(dicTypeId)) {
			GlobalType globalType = globalTypeService.get(new Long(dicTypeId));

			String[] ids = dicIds.split("[,]");
			if (ids != null) {
				for (String id : ids) {
					Dictionary dic = dictionaryService.get(new Long(id));
					dic.setItemName(globalType.getTypeName());
					dictionaryService.saveOrUpdate(dic);
				}
			}
		}
		return new Msg(true);
	}

	/**
	 * 批量删除
	 */
	@RequestMapping("multiDel")
	@ResponseBody
	public Msg multiDel(String[] ids) {
		if (ids != null) {
			for (String id : ids) {
				dictionaryService.remove(new Long(id));
			}
		}
		return new Msg(true);
	}

	/**
	 * 显示详细信息
	 */
	@RequestMapping("get")
	public void get(Long dicId, HttpServletResponse response) {
		Dictionary dictionary = dictionaryService.get(dicId);
		String json = new JSON(dictionary).buildWithFilters(3, "parentDict");
		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 添加及保存操作
	 */
	@RequestMapping("save")
	@ResponseBody
	public Msg save(Dictionary dictionary, Long parentId, Integer leaf) {
		//如果dictionary的dicId为空 则表示为 新增请求 如果不为空 则表示 修改请求
		if (dictionary.getDicId() != null) {
			// 修改
			Dictionary orgDic = dictionaryService.get(dictionary.getDicId());
			try {
				BeanUtil.copyNotNullProperties(orgDic, dictionary);
				dictionaryService.saveOrUpdate(orgDic);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			if(parentId != null){
				dictionary.setParentId(parentId);
				dictionary.setLeaf(leaf);
				dictionaryService.saveOrUpdate(dictionary);
			}
		}
		return new Msg(true);
	}

	/**
	 * 获得条目
	 */
	@RequestMapping("items")
	public void items(HttpServletResponse response) {
		List<String> list = dictionaryService.getAllItems();
		StringBuffer buff = new StringBuffer("[");
		for (String str : list) {
			buff.append("'").append(str).append("',");
		}
		if (list.size() > 0) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");
		ResponseUtils.renderJson(response, buff.toString());
	}
	

	public String getChildList(Long parentId){
		StringBuffer buff=new StringBuffer();
		String hql = " from Dictionary where parentDict.dicId=?";
		List<Dictionary> dicList=dictionaryService.findByHQL(hql, parentId);
		if(dicList.size()==0){
			buff.append("leaf:true,expanded:true},");
			return buff.toString(); 
		}else {
			buff.append("expanded:true,children:[");
			for(Dictionary dic:dicList){
				buff.append("{id:'"+dic.getDicId()).append("',text:'"+dic.getItemValue().trim()).append("',");
				buff.append(getChildList(dic.getDicId()));
			}
			buff.deleteCharAt(buff.length() - 1);
			buff.append("]},");
			return buff.toString();
		}
	}

	/**
	 * 取得数据字典树
	 */
	@RequestMapping("treeAll")
	public void tree(HttpServletResponse response) {
		List<TreeNode> nodes = new ArrayList<>();
		// 获得根结点
		List<Dictionary> dicList = dictionaryService.getByParent(0L, false);
		for(Dictionary dict : dicList) {
			TreeNode node = new TreeNode(dict.getDicId(), dict.getItemName());
			node.setSpread(true);
			nodes.add(node);
			// 设置子结点
			getChildren(node, dict);
		}
		String json = Jackson.me().toJson(nodes);
		ResponseUtils.renderJson(response, json);
	}


	@RequestMapping("deleteTree")
	@ResponseBody
	public Msg deleteTree(Long parentId, HttpServletResponse response) {
		Msg msg = new Msg();
		msg.setSuccess(false);
		msg.setMsg("删除出错");
		msg.setCode(500);
		String hql = "select d.dicId from Dictionary d where d.parentId = ?";
		if(parentId != null){
			try {
				List<Object> list = dictionaryService.findByHQL(hql, parentId);
				if(list.size() > 0) {
					msg.setSuccess(false);
					msg.setMsg("该类别含有子级元素");
					msg.setCode(500);
				} else {
					dictionaryService.remove(parentId);
					msg.setSuccess(true);
					msg.setMsg("删除成功");
					msg.setCode(200);
				}
			} catch (Exception e){
				e.printStackTrace();
				return msg;
			}
		}
		return msg;
	}
	/**
	 * 获得节点的子节点
	 * */
	private void getChildren(TreeNode node, Dictionary dict) {
		List<Dictionary> dicList = dictionaryService.getByParent(dict.getDicId(), false);
		if(dicList.size() > 0) {
			// 存在子节点
			List<TreeNode> children = new ArrayList<>();
			for(Dictionary d : dicList) {
				TreeNode n = new TreeNode(d.getDicId(), d.getItemName());
				children.add(n);
				// 设置子结点
				getChildren(n, d);
			}
			node.setChildren(children);
		}
	}

	/**
	 * iframe页面
	 */
	@RequestMapping("html/addTree")
	public String addUi(Model model, Long parentId) {
		Dictionary parent = dictionaryService.get(parentId);
		model.addAttribute("parent", parent);
		return "system/dictionary_form";
	}

	@RequestMapping("html/editTree")
	public String editUi(Long dicId, Model model) {
		Dictionary dict = dictionaryService.get(dicId);
		Dictionary parent = dictionaryService.get(dict.getParentId());
		
		model.addAttribute("dict", dict);
		model.addAttribute("parent", parent);
		
		return "system/dictionary_form";
	}

	@RequestMapping("/html/addLeaf")
	public String addLeaf(Model model, Long parentId, Long dictId) {
		Dictionary parent = dictionaryService.get(parentId);
		model.addAttribute("parent", parent);
		if(dictId != null){
			Dictionary dictionary = dictionaryService.get(dictId);
			model.addAttribute("dict", dictionary);
		}
		return "system/dictionary_leaf_form";
	}

}
